Skip to Content
Suffering builds character

6. 콜백 패턴의 단점 - 후속 처리

콜백 패턴의 또 다른 단점은 후속 처리가 복잡하다는 것

Q. result, global의 출력 값과 그 이유는?
problem.js
let global = 0; function setGlobalWith100() {     console.log('setGlobalWith100 started');     setTimeout(() => { global = 100; }, 1000);     console.log('setGlobalWith100 ended');     return global; } const result = setGlobalWith100(); console.log(result); console.log(global);

실행 결과


result: 0
global: 0
setTimeout(() => { global = 100 // 상위 스코프 변수인 global에 100으로 재할당 }, 1000);

→ 상위 스코프에 선언된 변수에 값 할당 불가

비동기 요청에 따른 응답 결과 값 처리

onload 이벤트는 callstack이 빈 후(하단 코드의 23번 라인의 console.log의 수행 종료 이후) 가장 마지막에 동작함

onload 프로퍼티에 화살표 함수가 이벤트 핸들러로 등록된 후, get() 함수는 내부의 비동기 요청 처리 결과를 받기 전에 먼저 종료됨

problem.js
let post; const get = (url) => {     console.log('get() started');     const xhr = new XMLHttpRequest();     xhr.open('GET', url);     xhr.send();     xhr.onload = () => {         if (xhr.status === 200) {             console.log(xhr.response);             post = JSON.parse(xhr.response); // 상위 스코프에 값을 할당             return JSON.parse(xhr.response); // 값 그 자체를 반환(?)         } else {             console.error(`${xhr.status} ${xhr.statusText}`);         }     }     console.log('get() ended'); } const url = 'https://jsonplaceholder.typicode.com/posts/1'; const getResult = get(url); console.log(getResult); // undefined console.log(post); // undefined

→ 정리하면,
비동기 처리 결과를 외부로 반환하거나 상위 스코프의 변수에 할당할 수 없고,
서버의 응답과 같이 비동기 함수의 결과값에 대한 처리는 비동기 함수 내부에서만 수행해야함

Last updated on